package cn.wolfcode.luowowo.service.util;

import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.common.util.DateUtil;
import cn.wolfcode.luowowo.common.util.JsonResult;
import cn.wolfcode.luowowo.common.util.KeysUtil;
import cn.wolfcode.luowowo.vo.StatisVO;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class StatisUtil {

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private ITravelService travelService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    private final static int VIEWNUM = 1;
    private final static int REPLYNUM = 2;
    private final static int FAVORNUM = 3;
    private final static int SHARENUM = 4;
    private final static int THUMBSUPNUM = 5;


    public StatisVO getStatisRedis(String key) {
        return JSON.parseObject(redisTemplate.opsForValue().get(key), StatisVO.class);
    }

    public StatisVO statisAndUpdateViewnum(Long detailId, int count, int type) {
        //todo  reids中的集合缓存
        StatisVO vo = new StatisVO();
        String key;
        if (type == StatisVO.USER_FAVOR_STRATERY) {
            key = KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString());
        } else {
            key = KeysUtil.TRAVEL_STATIS_VO.join(detailId.toString());
        }
        //判断redis中存不存在key
        if (redisTemplate.hasKey(key)) {
            this.setStatis(detailId, count, StatisUtil.VIEWNUM, key);
            //存在的话2

        } else {
            if (type == StatisVO.USER_FAVOR_STRATERY) { //攻略
                StrategyDetail detail = strategyDetailService.get(detailId);
                copyStrategyProperties(detail, vo);
            } else { //游记
                Travel travel = travelService.get(detailId);
                copyTravelProperties(travel, vo);
            }
            //如果不存在的话
            redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
        }
        return vo;
    }

    public void setReplynumStatisRedis(Long detailId, int i, String sKey) {
        setStatis(detailId, i, StatisUtil.REPLYNUM, sKey);
    }

    public JsonResult favor(Long sid, Long uId, int userFavorType) {
        return getJsonResult(sid, uId, userFavorType, StatisUtil.FAVORNUM);
    }

    public JsonResult strategyThumbup(Long sId, Long uId, int userFavorType) {
        return getJsonResult(sId, uId, userFavorType, StatisUtil.THUMBSUPNUM);
    }


    private JsonResult getJsonResult(Long sid, Long uId, int userFavorType, int type) {
        List<Long> list = new ArrayList<>();
        String UFKey;
        String UTKey;
        String sKey;
        if (userFavorType == StatisVO.USER_FAVOR_STRATERY) {
            UFKey = KeysUtil.USER_STRATERY_STATIS_FAVOR.join(sid.toString());  //攻略收藏数
            UTKey = KeysUtil.STRATERY_STATIS_THUMBSUPNUM.join(uId.toString(),sid.toString()); //攻略点赞数
            sKey = KeysUtil.STRATEGY_STATIS_VO.join(sid.toString());
        } else {
            UFKey = KeysUtil.USER_TRAVEL_STATIS_FAVOR.join(sid.toString());
            UTKey = KeysUtil.TRAVEL_STATIS_THUMBSUPNUM.join(uId.toString(),sid.toString());
            sKey = KeysUtil.TRAVEL_STATIS_VO.join(sid.toString());
        }
        if (type == StatisUtil.FAVORNUM){
            if (redisTemplate.hasKey(UFKey)) {
                list = JSON.parseArray(redisTemplate.opsForValue().get(UFKey), Long.class);
                if (list != null && list.contains(sid)) {
                    list.remove(sid);
                    redisTemplate.opsForValue().set(UFKey, JSON.toJSONString(list));
                    return JsonResult.FAIL.addData(setStatis(sid, -1, StatisUtil.FAVORNUM, sKey));
                }
            }
            list.add(sid);
            redisTemplate.opsForValue().set(UFKey, JSON.toJSONString(list));

        }else {
            if (redisTemplate.hasKey(UTKey)) {
                return JsonResult.FAIL;
            }
            redisTemplate.opsForValue().set(UTKey, "1");
        }
        return JsonResult.SUCCESS.addData(this.setStatis(sid, 1, type, sKey));


       /* //先判断redis中是否存在该key
        if (redisTemplate.hasKey(uKey)) {
            //存在的时候
            list = JSON.parseArray(redisTemplate.opsForValue().get(UFKey), Long.class);
            if (list != null && list.contains(sid)) {
                if (type == StatisUtil.FAVORNUM) {
                    list.remove(sid);
                    redisTemplate.opsForValue().set(uKey, JSON.toJSONString(list));
                    return JsonResult.FAIL.addData(setStatis(sid, -1, StatisUtil.FAVORNUM, sKey));
                } else {
                    return JsonResult.FAIL;
                }

                if (type == StatisUtil.FAVORNUM) {
                    list.remove(sid);
                    redisTemplate.opsForValue().set(UFKey, JSON.toJSONString(list));
                    return JsonResult.FAIL.addData(setStatis(sid, -1, StatisUtil.FAVORNUM, sKey));
                }
                return JsonResult.FAIL;

            }
        }
        //其他情况
            if (type == StatisUtil.THUMBSUPNUM) {
                Date now = new Date();
                redisTemplate.opsForValue().set(UFKey, JSON.toJSONString(list), DateUtil.getDateBetween(now, DateUtil.getEndDate(now)), TimeUnit.SECONDS);
            } else {
                list.add(sid);
                redisTemplate.opsForValue().set(UFKey, JSON.toJSONString(list));
            }

        return JsonResult.SUCCESS.addData(this.setStatis(sid, 1, type, sKey));*/
    }

    private StatisVO setStatis(Long detailId, int i, int type, String key) {
        StatisVO vo = this.getStatisRedis(key);

        if (vo == null) {
            vo = statisAndUpdateViewnum(detailId,i,
                    key.equals(KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString()))?StatisVO.USER_FAVOR_STRATERY:StatisVO.USER_FAVOR_TRAVEL);
        }
        String commendKey = vo.isIsabroad() ? KeysUtil.FOREIGN_STRATERY_STATIS_COMMEND_SORT.getName()
                : KeysUtil.INLAND_STRATERY_STATIS_COMMEND_SORT.getName();
        //防止没有初始化redis 在游记列表直接点顶 报空指针
        switch (type) {
            case (StatisUtil.VIEWNUM):
                vo.setViewnum(vo.getViewnum() + i);
                if (key.equals(KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString())) ) {
                    redisTemplate.opsForZSet().incrementScore(KeysUtil.STRATERY_STATIS_HOT_COMMEND_SORT.getName(),
                            KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString()), i);
                }
                break;
            case (StatisUtil.REPLYNUM):
                vo.setReplynum(vo.getReplynum() + i);
                if (key.equals(KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString()))) {
                    redisTemplate.opsForZSet().incrementScore(KeysUtil.STRATERY_STATIS_HOT_COMMEND_SORT.getName(),
                            KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString()), i);
                }
                break;
            case (StatisUtil.FAVORNUM):
                vo.setFavornum(vo.getFavornum() + i);
                if (key.equals(KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString()))) {
                    redisTemplate.opsForZSet().incrementScore(commendKey,
                            KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString()), i);
                }
                break;
            case (StatisUtil.SHARENUM):
                vo.setSharenum(vo.getSharenum() + i);
                break;
            case (StatisUtil.THUMBSUPNUM):
                vo.setThumbsupnum(vo.getThumbsupnum() + i);
                if (key.equals(KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString()))) {
                    redisTemplate.opsForZSet().incrementScore(commendKey,
                            KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString()), i);
                }
                break;
        }
        redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
        return vo;
    }

    public void copyStrategyProperties(StrategyDetail detail, StatisVO vo) {
        try {
            BeanUtils.copyProperties(vo, detail);
            vo.setDestId(detail.getDest().getId());
            vo.setDestName(detail.getDest().getName());
            vo.setStrategyId(detail.getId());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    public void copyTravelProperties(Travel travel, StatisVO vo) {
        try {
            BeanUtils.copyProperties(vo, travel);
            vo.setDestId(travel.getDest().getId());
            vo.setTravelId(travel.getId());
            vo.setDestName(travel.getDest().getName());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }


    public boolean checkFavor(Long id, String ukey) {
        String s = redisTemplate.opsForValue().get(ukey);
        List<Long> list = JSON.parseArray(s, Long.class);
        return list != null && list.contains(id);
    }
}
